package cn.kevinking.ai.mcp.provider.web;

import cn.kevinking.ai.mcp.provider.ex.McpProviderRequestMethodRunException;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolverComposite;
import org.springframework.web.method.support.InvocableHandlerMethod;
import org.springframework.web.servlet.function.ServerRequest;

import java.lang.reflect.Method;

/**
 * @author jinkw
 */
public class RequestBodyArgumentResolver {
    private final HandlerMethodArgumentResolverComposite resolverComposite;

    public RequestBodyArgumentResolver(HandlerMethodArgumentResolverComposite resolverComposite) {
        this.resolverComposite = resolverComposite;
    }

    public Object resolveArgument(ServerRequest request, Object bean, Method method) {
        ServletWebRequest webRequest = new ServletWebRequest(request.servletRequest());
        InvocableHandlerMethod invocable = new InvocableHandlerMethod(bean, method);
        // 直接使用Spring提供的参数解析方法
        invocable.setHandlerMethodArgumentResolvers(resolverComposite);
        invocable.setParameterNameDiscoverer(new DefaultParameterNameDiscoverer());
        Object methodResult;
        try {
            methodResult = invocable.invokeForRequest(webRequest, null);
        } catch (Exception e) {
            throw new McpProviderRequestMethodRunException();
        }
        return methodResult;
    }
}
